﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSoict.Models;
using Newtonsoft.Json;

namespace MVCSoict.Controllers
{
    public class ProjectController : Controller
    {
        private staffsoictEntities1 db = new staffsoictEntities1();
        private JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        };
        // GET: /Project/
        public ActionResult Index()
        {
            return View(db.Projects.ToList());
        }

        public string Select(string keyword, int page, int pagesize)
        {
            string jsonResult = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "project_select"))
                {
                    using (var context = new staffsoictEntities1())
                    {
                        var projects = from p in context.Projects
                                       where p.description.Contains(keyword)
                                       orderby p.id
                                       select p;

                        var pageData = projects.Skip((page - 1) * pagesize).Take(pagesize).ToList();
                        foreach (var pro in pageData)
                        {
                            jsonResult += JsonConvert.SerializeObject(pro, jsonSettings);
                        }
                    }
                }
            }
            return jsonResult;
        }

        public string Add([Bind(Include = "description,year")] Project project) //đang bị lỗi
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "project_add"))
                {
                    try
                    {
                        project.id = GetNextId();
                        db.Projects.Add(project);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(project, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string GetNextId()
        {
            var projects = from p in db.Projects
                        orderby p.id
                        select p;
            int count = projects.Count();
            string id = string.Empty;
            string nextid = string.Empty;
            int delta = 0;
            if (count > 0)
            {
                id = projects.ToList()[count - 1].id;
                int y = Convert.ToInt32(id[4].ToString());
                if (y < 9)
                {
                    delta = 1;
                }
                if (y >= 9 && y < 99)
                {
                    delta = 2;
                }
                if (y >= 99 && y < 999)
                {
                    delta = 3;
                }
                for (int i = 0; i < (id.Count() - delta); i++)
                {
                    nextid += id[i].ToString();
                }
                nextid += (y + 1).ToString();
            }
            else
            {
                nextid = "P0000";
            }
            return nextid;
        }

        public string Xoa(string id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "project_xoa"))
                {
                    Project project = db.Projects.Find(id);
                    try
                    {
                        db.Projects.Remove(project);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(project, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        //tested
        public string Update([Bind(Include = "id,description,year")] Project project)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "project_update"))
                {
                    try
                    {
                        db.Entry(project).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(project, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Get(string id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "project_get"))
                {
                    try
                    {
                        var projects = from p in db.Projects
                                       where p.id.Equals(id)
                                       select p;
                        if ((projects.ToList<Project>().Count() > 0))
                            res = JsonConvert.SerializeObject(projects.ToList<Project>()[0], jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        // GET: /Project/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        // GET: /Project/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Project/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="pid,description,year")] Project project)
        {
            if (ModelState.IsValid)
            {
                db.Projects.Add(project);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(project);
        }

        // GET: /Project/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        // POST: /Project/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="pid,description,year")] Project project)
        {
            if (ModelState.IsValid)
            {
                db.Entry(project).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(project);
        }

        // GET: /Project/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        // POST: /Project/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Project project = db.Projects.Find(id);
            db.Projects.Remove(project);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
